package com.chanjiedata.changbs.module.count;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.adapter.TaijunAdapter;
import com.chanjiedata.changbs.base.BaseFragment;
import com.chanjiedata.changbs.dialog.SelectMonthDialog;
import com.chanjiedata.changbs.help.UserHelper;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.Mystock;
import com.chanjiedata.changbs.proto.Statistics;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.google.android.material.tabs.TabLayout;
import com.google.protobuf.InvalidProtocolBufferException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import kale.ui.view.dialog.EasyDialog;

/**
 * Created by Administrator on 2018/2/2 0002.
 */

public class CountFifthFragment extends BaseFragment {


    Unbinder unbinder;
    @BindView(R.id.tab_layout)
    TabLayout tablayout;
    @BindView(R.id.mPieChart)
    PieChart mPieChart;
    @BindView(R.id.ll_content_one)
    LinearLayout llContentOne;
    @BindView(R.id.tab_layout_two)
    TabLayout tabLayoutTwo;
    @BindView(R.id.ll_content_two)
    LinearLayout llContentTwo;
    @BindView(R.id.rg_type)
    RadioGroup rgType;
    @BindView(R.id.btn_one)
    RadioButton btnOne;
    @BindView(R.id.btn_two)
    RadioButton btnTwo;
    @BindView(R.id.tv_select_time)
    TextView tvSelectTime;
    @BindView(R.id.tv_total_tai_jun)
    TextView tvTotalTaiJun;
    @BindView(R.id.tv_total_tai_jun_shu)
    TextView tvTotalTaiJunShu;
    @BindView(R.id.tv_select_time_two)
    TextView tvSelectTimeTwo;
    @BindView(R.id.tv_pai_xun)
    TextView tvPaiXun;
    @BindView(R.id.rv_recycle_view)
    RecyclerView rvRecycleView;


    private TaijunAdapter mAdapter;
    private List<Statistics.member_average> datas_average = new ArrayList<>();
    private ArrayList<PieEntry> pieEntries = new ArrayList<>();
    private String[] pieColor;
    private List<Mystock.myMachine.List> datas = new ArrayList<>();
    private String search_time_end = new SimpleDateFormat("yyyy-MM").format(new Date());
    private String search_time_end_two = new SimpleDateFormat("yyyy-MM").format(new Date());
    private String goods_id = "";
    private String goods_id_two = "";
    private String sort_type = "1";   //排序类型：1-从高到低；2-从低到高

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_count_fifth;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initView() {
        tvSelectTime.setText(search_time_end);
        tvSelectTimeTwo.setText(search_time_end_two);
        pieColor = getActivityContext().getResources().getStringArray(R.array.array_seven_color);
        initListener();
        initPerChat();
        initRecyclerView();
        initXinahaoData();
    }


    private void initRecyclerView() {
        rvRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
        rvRecycleView.setAdapter(mAdapter = new TaijunAdapter(mContext, datas_average));
        mAdapter.bindToRecyclerView(rvRecycleView);
        mAdapter.setEmptyView(R.layout.recycle_empty);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(mContext,CountFiveActivity.class);
            intent.putExtra("name",datas_average.get(position).getName());
            intent.putExtra("member_id",datas_average.get(position).getMemberId());
            intent.putExtra("time",search_time_end_two);
            intent.putExtra("position",tabLayoutTwo.getSelectedTabPosition());
            startActivity(intent);
        });
        //添加分割线
        rvRecycleView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
    }

    /**
     * 初始化监听器
     */
    private void initListener() {

        rgType.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.btn_one) {
                llContentOne.setVisibility(View.VISIBLE);
                llContentTwo.setVisibility(View.GONE);
            } else {

                llContentOne.setVisibility(View.GONE);
                llContentTwo.setVisibility(View.VISIBLE);
            }
        });

        tvSelectTime.setOnClickListener(v -> {
            SelectMonthDialog.Builder builder = new SelectMonthDialog.Builder(mContext);
            builder.setOnDialogClickListener((view, month) -> {
                search_time_end = month;
                tvSelectTime.setText(search_time_end);
                loadPerChartData();
            });
            EasyDialog build = builder.build();
            build.setCancelable(true);
            build.show(getChildFragmentManager());
        });

        tvSelectTimeTwo.setOnClickListener(v -> {
            SelectMonthDialog.Builder builder = new SelectMonthDialog.Builder(mContext);
            builder.setOnDialogClickListener((view, month) -> {
                search_time_end_two = month;
                tvSelectTimeTwo.setText(search_time_end_two);
                loadPerChartData();
            });
            EasyDialog build = builder.build();
            build.setCancelable(true);
            build.show(getChildFragmentManager());
        });

        tvPaiXun.setOnClickListener(v -> {
            if (sort_type.equals("1"))
            {
                sort_type = "2";
                tvPaiXun.setText("按台均低到高排序");
            }else
            {
                sort_type = "1";
                tvPaiXun.setText("按台均高到低排序");
            }
            LoadTaiJunListData();
        });

    }

    private void loadPerChartData() {
        Statistics.get_sn_average.Builder builder = Statistics.get_sn_average.newBuilder();
        builder.setMemberId(UserHelper.getUser().getMember_id()).setMonth(search_time_end).setGoodsId(goods_id);
        NetworkManager.INSTANCE.post(Apis.get_sn_average, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Statistics.get_sn_average datas = Statistics.get_sn_average.parseFrom(bytes);
                List<Statistics.basis> lists = datas.getAverageList();
                setPerChartData(lists, datas.getAverageAmount(), datas.getNum());
            }

            @Override
            public void onError(int code, String errorMessage) {
            }
        });
    }


    private void setPerChartData(List<Statistics.basis> lists, String average_amount, String num) {
        pieEntries.clear();
        ArrayList<Integer> colors = new ArrayList<Integer>();
        tvTotalTaiJun.setText(String.format("￥%s", average_amount));
        tvTotalTaiJunShu.setText(num + "台");
        for (int i = 0; i < lists.size(); i++) {
            colors.add(Color.parseColor(pieColor[i]));
            if (Float.valueOf(num) == 0) {
                pieEntries.add(new PieEntry(1, lists.get(i).getName() + " " + lists.get(i).getNum() + "台"));
            } else {
                pieEntries.add(new PieEntry(Float.valueOf(lists.get(i).getNum()), lists.get(i).getName() + " " + lists.get(i).getNum() + "台"));
            }
        }
        PieDataSet dataSet = new PieDataSet(pieEntries, "");
        //设置饼状Item之间的间隙
        dataSet.setSliceSpace(2f);
        //数据和颜色
        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setDrawValues(false);
        mPieChart.setData(data);
        //刷新
        mPieChart.animateXY(500,500);
    }

    private void initPerChat() {
        mPieChart.setRotationEnabled(false);// 可以手动旋转
        mPieChart.setUsePercentValues(false);//显示成百分比
        mPieChart.setDrawEntryLabels(false);
        mPieChart.setTouchEnabled(false);
        mPieChart.setDrawCenterText(false);

        mPieChart.getDescription().setEnabled(false); //取消右下角描述
        //去掉半透明
        mPieChart.setTransparentCircleAlpha(0);
        mPieChart.getLegend().setEnabled(true);


        Legend l = mPieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setFormSize(10);                      //设置图例的大小
        l.setFormToTextSpace(10f);              //设置每个图例实体中标签和形状之间的间距
        l.setForm(Legend.LegendForm.CIRCLE); //设置图例的形状

        l.setFormSize(13);                      //设置图例的大小

        l.setTextSize(13f);                      //设置图例标签文本的大小

        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);

        l.setXOffset(30);                      //设置比例块Y轴偏移量


        l.setXEntrySpace(30);

        l.setWordWrapEnabled(true);
    }


    //设置tablayout
    /**
     * 初始化折线图tab
     */
    private void initTabLayout() {
        for(int i=0;i<datas.size();i++){
            tablayout.addTab(tablayout.newTab());
            tablayout.getTabAt(i).setText(datas.get(i).getGoodsSerial());
        }
        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if(tab==null|| tab.getText() == null)
                {
                    return;
                }
                scaleAnima(1.0f,1.15f,tab.view);
                goods_id = datas.get(tab.getPosition()).getGoodsId();
                loadPerChartData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if(tab==null|| tab.getText() == null)
                {
                    return;
                }
                scaleAnima(1.15f,1.0f,tab.view);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        scaleAnima(1.0f,1.15f,tablayout.getTabAt(0).view);
    }

    private void scaleAnima(float v,float v2, TabLayout.TabView title) {
        AnimationSet animationSet = new AnimationSet(true);
        ScaleAnimation scaleAnimation = new ScaleAnimation(
                v, v2, v, v2,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(100);//动画持续时间
        animationSet.addAnimation(scaleAnimation);//保存动画效果到。。
        animationSet.setFillAfter(true);//结束后保存状态
        title.startAnimation(animationSet);//设置给控件

    }


    //设置tablayout
    private void initTabLayoutTwo() {
        for(int i=0;i<datas.size();i++){
            tabLayoutTwo.addTab(tabLayoutTwo.newTab());
            tabLayoutTwo.getTabAt(i).setText(datas.get(i).getGoodsSerial());
        }
        tabLayoutTwo.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if(tab==null|| tab.getText() == null)
                {
                    return;
                }
                scaleAnima(1.0f,1.15f,tab.view);
                goods_id_two = datas.get(tab.getPosition()).getGoodsId();
                LoadTaiJunListData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if(tab==null|| tab.getText() == null)
                {
                    return;
                }
                scaleAnima(1.15f,1.0f,tab.view);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        scaleAnima(1.0f,1.15f,tabLayoutTwo.getTabAt(0).view);
    }


    @Override
    protected void init() {
    }


    private void initXinahaoData() {
        NetworkManager.INSTANCE.post(Apis.myMachine, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                datas = Mystock.myMachine.parseFrom(bytes).getListList();
                goods_id = datas.get(0).getGoodsId();
                goods_id_two = datas.get(0).getGoodsId();
                initTabLayout();
                initTabLayoutTwo();
                loadPerChartData();
                LoadTaiJunListData();
            }

            @Override
            public void onError(int errorCode, String errorMessage) {

            }
        });
    }

    private void LoadTaiJunListData() {

        Statistics.get_average_list.Builder builder = Statistics.get_average_list.newBuilder();
        builder.setGoodsId(goods_id_two).setMonth(search_time_end_two).setSortType(sort_type);
        NetworkManager.INSTANCE.post(Apis.get_average_list, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                datas_average = Statistics.get_average_list.parseFrom(response).getListList();
                mAdapter.replaceData(datas_average);
                mAdapter.loadMoreEnd();
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
            }
        });
    }

    public void reLoadData() {
        loadPerChartData();
        LoadTaiJunListData();
    }

}
